<?php


namespace app\api\controller;


use think\Db;

class Crontab
{
    public function loop()
    {
        $sql_arr = Db::name('crontab')->select();

        $data = Db::connect([
            'type' => 'mysql',
            'hostname' => '127.0.0.1',
            'database' => 'network',
            'username' => 'root',
            'password' => 'root'
        ])->query('select * from alerts');

        /*$data = Db::connect([
            'type' => 'mysql',
            'hostname' => $sql_arr['ip'],
            'database' => 'zabbix',
            'username' => '',
            'password' => ''
        ])->query($sql_arr['sql']);*/

        return json($sql_arr);
    }

    public function carry()
    {
        $now_time = date('H:i');
//        $data = Db::name('crontab')->field('id, FROM_UNIXTIME(time, "%Y-%m-%d") as time')->select();
        $sql = Db::query('select * from crontab where FROM_UNIXTIME(time, "%H:%i") = "'.$now_time.'" limit 1');

        if ($sql && $sql[0]['active'] == 0) {
            $host = Db::name('server')->where('id',$sql[0]['server'])->field('ip, database, username, password')->find();
            if ($host) {
                /*$data = Db::connect([
                    'type' => 'mysql',
                    'hostname' => $host['ip'],
                    'database' => $host['database'],
                    'username' => $host['username'],
                    'password' => $host['password']
                ])->query($sql[0]['sql']);*/
                $data = Db::name('alarm_test')->field('host,name,description,priority,clock')->select();    //测试数据

                if ($data) {
                    foreach ($data as $k=>&$v) {
                        $v['dept_id'] = $sql[0]['dept_ids'];
                        $v['type'] = $sql[0]['type'];
                    }
                    $firstday = date('Y-m-01', strtotime($data[0]['clock']));
                    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

                    // 需要加上时间判定,根据获取到的数据中的时间得到指定的月份
                    $del = Db::name('alarm_data')
                        ->where('dept_id = '.$sql[0]['dept_ids'].' and type = '.$sql[0]['type'])
                        ->where('clock','between',[$firstday, $lastday])
                        ->delete();
                    $all = Db::name('alarm_data')->insertAll($data);
                    if ($all) {
                        Db::name('crontab')->where('id', $sql[0]['id'])->update(['active'=>1]);
                        return 1;
                    } else {
                        return 0;
                    }
                } else {
                    return 1;
                }
            }
        } else {
            return 1;
        }
    }
}